#!/usr/bin/perl -w

# TODO: Handle undefined $1
# TODO: Lock files

use MIME::Base64;
use LWP::UserAgent;
use Data::Dumper;
use XML::XPath;
use POSIX 'strftime';
use Digest::MD5;

use FCTranscode;

$md_num = $#ARGV;
for (my $count = 0; $count <= $md_num; $count++){

	$ARGV[$count] =~ /^([\w+\ ]+):(.*)/;
	if ($2 eq "[$1]") { $metadata{$1} = ""; }
	else { $metadata{$1} = $2; }
}

#if	($metadata{'Stored On'} eq "Library")	{ $store_location = $library_location.$metadata{'Location'}.'/'; }
#elsif	($metadata{'Stored On'} eq "Media")	{ $store_location = $media_location; }	
#else	{ print "ERROR:0000: File in unknown location for add_eprint_item.pl ."; exit 1; }

$ua = LWP::UserAgent->new;

#$ua->agent("add_item.pl/0.1");

$req = HTTP::Request->new(POST => "http://$remote_host$path");
$req->protocol('HTTP/1.1');

$req->content_type('text/xml');

local $/=undef;

open (FH, "<", "/Users/ecstv/fctranscode/blank_item.xml") or die("Couldn't open file: $!");
$plain = <FH>;
close FH;

$plain =~ s/TITLE/$metadata{'Title'}/g;
$plain =~ s/DESCRIPTION/$metadata{'Description'}/g;
$plain =~ s/MIMETYPE/$metadata{'Mime Type'}/g;
$plain =~ s/URL/http:\/\/$local_host\/$metadata{'Stored On'}\/$metadata{'Location'}\/$metadata{'FileName'}/g;
$plain =~ s/FILENAME/$metadata{'FileName'}/g;

$metadata{'Creation Date'} =~ /([\d\-]{10})/;
my $qdate = $1;
$plain =~ s/DATE/$qdate/g;

$current_time = strftime "%Y-%m-%d %H:%M:%S", localtime;
$plain =~ s/LOCALTIME/$current_time/g;

$fsize = -s "$store_location/$metadata{'Stored On'}/$metadata{'Location'}/$metadata{'FileName'}";
$plain =~ s/FILESIZE/$fsize/g;

my $ctx = Digest::MD5->new;
open(FH, "<", "$store_location/$metadata{'Stored On'}/$metadata{'Location'}/$metadata{'FileName'}");
$ctx->addfile(FH);
$hash = $ctx->hexdigest;
$plain =~ s/HASH/$hash/g;
close FH;

# Get media duration (maybe put a few checks/warnings?)
unless (-e $mediainfo) {
        error_die("ERROR:3002: mediainfo not found.");
}
$raw_minfo = `$mediainfo --Output=XML \'$store_location/$metadata{'Stored On'}/$metadata{'Location'}/$metadata{'FileName'}\'`;
$xml_content = XML::XPath->new($raw_minfo)      or error_die("ERROR:3003: Could not instantiate XPath.");
# Not sure if the bellow should be an error or warning. Need to match the quickwarn and ERROR:
$duration_raw = $xml_content->getNodeText('/Mediainfo/File/Video/Duration') or quick_warn("ERROR:3004: Invalid node path for mediainfo XML.");

# Looks like then warnings comes from $1 been undefined. TODO - Check $1 before assignment
$duration_raw =~ /(\d+)h/;
$hours = $1;
$duration_raw =~ /(\d+)mn/;
$mins = $1;
$duration_raw =~ /(\d+)s/;
$secs = $1;

$totaltime = "$secs";
if (defined $mins)	{ $totaltime .= "$mins:$totaltime"; }
if (defined $hours) 	{ $totaltime .= "$hours:$totaltime"; }


print $plain;

$http_content = $plain;

# Won't be using XML:: (below) for now. 

#my $file = "/Users/ecstv/fctranscode/blank_item.xml";
#my $xs = XML::Simple->new();

#my $eprint = $xs->XMLin($file,
#			KeepRoot => 1,
#			);

#Make the changes to $eprint

#print Dumper($eprint);

#$xs->XMLout($eprint,
#	KeepRoot => 1,
#	OutputFile => $file.".out",
#	XMLDecl => "<?xml version='1.0' ?>",
#	);


$req->content($http_content);

$req->header('Authorization', 'Basic '.encode_base64("$user:$pass"));

$req->header('Content-Length', length($http_content));

$req->header('X-Verbose', 'true');
$req->header('X-Packaging','http://eprints.org/ep2/data/2.0');

$res = $ua->request($req);

if ($res->is_success) {
	print $res->content;
}
else {
	write_log($res->status_line."\n".$res->content);
	print $res->status_line."\n".$res->content; }

